<?php

class _F_EXTENSION_LESS_JS_ extends _F_EXTENSION_ {
	
	public $mode = 'client-side';
	public $runtime_path = '/runtime/less';
	public $less_js_verions = '1.2.2';
	public $prev_callback;
	
	public function __construct() {
		f()->register_method('less_js',array($this,'less_js'));
		$this->prev_callback = f()->register_method(
			'post_process_callback',array($this,'_f_callback_'));
	}
	
	public function less_js() {
		return $this;
	}
	
	public function _f_callback_() {
		$styles = array();
		$insert_script = false;
		foreach (f()->style()->styles as $style => $attr) {
			if (preg_match("/\.less$/",$style)) {
				$file = f()->base_path.$style;
				if (file_exists($file) && $this->mode === 'server-side') {
					$md5 = md5_file($file);
					$style = $this->runtime_path.'/c'.$md5.'.css';
					$target = f()->base_path.$style;
					if (!file_exists($target)) {
						$dir = f()->base_path.$this->runtime_path;
						if (!file_exists($dir)) mkdir($dir,0777,true);
						require_once dirname(__FILE__).'/lib/lessc.inc.php';
						$less = new lessc($file);
						file_put_contents($target,$less->parse());
					}
					if (isset($attr['rel'])) unset($attr['rel']);
				} else {
					// f()->script()->scripts = array_merge(
					// 	array('@/extensions/less-js/scripts/less.min.js' => null),
					// 	f()->script()->scripts);
					$insert_script = true;
					$attr['rel'] = 'stylesheet/less';
				}
			}
			$styles[$style] = $attr;
		}
		f()->style()->styles = $styles;
		// high priority, must run before the style post process
		if (isset($this->prev_callback)) call_user_func($this->prev_callback);
		// add the script after the css files
		if ($insert_script) {
			$buffer = '<script src="'.f()->url_base.
				'/extensions/less-js/scripts/less-'.
				$this->less_js_verions.".min.js\"></script>\r\n";
			f()->content = preg_replace('/<\/(head\s*)/im',
				"$buffer</$1",f()->content);
		}
	}
	
}

new _F_EXTENSION_LESS_JS_;
